
<template>
  <div class="contract-model-page" v-loading="state.loading">
    <div class="query-form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="客户">
            <el-select
                v-model="state.queryData.CustCode"
                placeholder="请选择客户"
                size="small"
                clearable
                filterable
            >
              <el-option
                  v-for="item in cubasdoc.data"
                  :key="item.cCusCode"
                  :label="item.ccusname"
                  :value="item.cCusCode"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="合同类别">
            <el-select
                v-model="state.queryData.Type"
                placeholder="请选择合同类别"
                size="small"
                clearable
            >
              <el-option label="正式合同" value="0" />
              <el-option label="虚拟合同" value="1" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="合同类型">
            <el-select
                v-model="state.queryData.ContractType"
                placeholder="请选择合同类型"
                size="small"
                clearable
            >
              <el-option label="销售合同" value="1" />
              <el-option label="采购合同" value="2" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="状态">
            <el-select
                v-model="state.queryData.State"
                placeholder="请选择状态"
                size="small"
                clearable
            >
              <el-option label="开立" value="0" />
              <el-option label="已审核" value="1" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="制单日期">
            <el-date-picker
                v-model="state.queryData.CreateFrom"
                type="daterange"
                size="small"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="制单人">
            <el-input
                v-model="state.queryData.CreateBy"
                placeholder="请输入制单人"
                size="small"
                clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <div class="query-buttons">
            <el-button type="primary" @click="conditionEnter(state.queryData)">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="table-toolbar">
      <el-button type="danger" @click="addHandle()" v-if="checkPermission('新增', state.roleList)">新增</el-button>
      <el-button type="danger" @click="deleteHandles" :disabled="!state.ids.length" v-if="checkPermission('删除', state.roleList)">删除</el-button>
    </div>

    <el-table
        :data="state.table.data"
        border
        row-key="Id"
        @selection-change="selecUpdateChange"
    >
      <el-table-column type="selection" fixed />
      <el-table-column prop="CustCode" label="客户编码" min-width="120" />
      <el-table-column prop="CustName" label="客户名称" min-width="200" />
      <el-table-column prop="versionNum" label="版本号" min-width="220" />
      <el-table-column prop="CustAdd" label="客户地址" min-width="200" />
      <el-table-column prop="Type" label="合同类型" min-width="120" >
        <template #default="scope">
          <el-tag :type="scope.row.Type === '0'? 'primary':'success'">
            {{ scope.row.Type === '0' ?'正式合同' :'虚拟合同' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="IsMoudel" label="是否合同模板" min-width="120" >
        <template #default="scope">
          <el-tag :type="scope.row.IsMoudel? 'primary':'success'">
            {{ scope.row.IsMoudel?'是' :'非标合同' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="State" label="状态" min-width="220" >
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.State=='0'">开立</el-tag>
          <el-tag type="success" v-if="scope.row.State=='2'">已审核</el-tag>
          <el-tag type="primary" v-if="scope.row.State=='3'">已关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="BGState" label="变更状态" min-width="220" >
        <template #default="scope">
          <el-tag type="info" v-if="scope.row.BGState=='0' || scope.row.BGState==null">未变更</el-tag>
          <el-tag type="warning" v-if="scope.row.BGState=='3'">变更不通过</el-tag>
          <el-tag type="success" v-if="scope.row.BGState=='2'">变更通过</el-tag>
          <el-tag type="primary" v-if="scope.row.BGState=='1'">变更送审中</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createDate" label="创建时间" min-width="220" >
        <template #default="scope">
          <div>{{ parseTime(scope.row.createDate) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="320" fixed="right" >
        <template #default="scope">
          <el-button link @click="handleView(scope.row)" type="primary">详情</el-button>
          <el-button link @click="handlEedit(scope.row)" type="primary" v-if="scope.row.State==='0' && checkPermission('修改', state.roleList)">编辑</el-button>
          <el-button link @click="handlCheck(scope.row,'2')" type="primary" v-if="scope.row.State==='0' && checkPermission('审核', state.roleList)">审核</el-button>
          <el-button link @click="handlCheck(scope.row,'0')" type="primary" v-if="['2'].includes(scope.row.State) && checkPermission('弃审', state.roleList)">弃审</el-button>
          <el-button link @click="handlCheck(scope.row,'3')" type="primary" v-if="scope.row.State!=='3' && checkPermission('关闭', state.roleList)">关闭</el-button>
          <el-button link @click="versionHandle(scope.row)" type="primary" v-if="checkPermission('查看版本', state.roleList)">查看版本</el-button>
          <el-button link @click="printHandle(scope.row)" type="primary" v-if="checkPermission('打印', state.roleList)">打印</el-button>
          <el-button link @click="deleteHandles(scope.row)" type="danger" v-if="scope.row.State==='0' && checkPermission('删除', state.roleList)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="sizeChange"
        @current-change="pageChange"
        :current-page="state.table.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="state.table.pageSize"
        :total="state.table.total"
        layout="total, sizes, prev, pager, next, jumper"
        background      style="margin-top: 20px; text-align: right;"
    />

    <!--  新增 / 修改对话框 -->
    <el-dialog :title="state.title" width="90%" v-model="state.dialogSelectEnt" :close-on-click-modal="false">
      <div>
        <el-tabs type="border-card" @tab-change="selecttab">
          <el-tab-pane label="基本信息">
            <EntryBaseInfo :disabled="state.disabled" ref="formRef" :isBg="state.isBg" :baseInfo="state.formData.Main" :rules="state.rules" :tremZF="state.formData.TremZF" :subList="state.formData.SubList" Id="10007"></EntryBaseInfo>
          </el-tab-pane>

          <!--  1 质量保证条款 2所有权条款 3解决争议条款 4不可抗力条款 5解除合同条款 6违约条款 7支付条款        -->
          <el-tab-pane label="质量保证条款">
            <EntryQualityInfo :disabled="state.disabled" ref="TremQA" :Trem="state.formData.TremQA" Id="10001" title="质量保证条款"></EntryQualityInfo>
          </el-tab-pane>
<!--          <el-tab-pane label="所有权利转移条款">
            <EntryQualityInfo :disabled="state.disabled" ref="TremTO" :Trem="state.formData.TremTO" Id="10002" title="所有权利转移条款"></EntryQualityInfo>
          </el-tab-pane>
          <el-tab-pane label="解决争议条款">
            <EntryQualityInfo :disabled="state.disabled" ref="TremDR" :Trem="state.formData.TremDR" Id="10003" title="解决争议条款"></EntryQualityInfo>
          </el-tab-pane>
          <el-tab-pane label="不可抗力条款">
            <EntryQualityInfo :disabled="state.disabled" ref="TremFM" :Trem="state.formData.TremFM" Id="10004" title="不可抗力条款"></EntryQualityInfo>
          </el-tab-pane>
          <el-tab-pane label="违约条款">
            <EntryQualityInfo :disabled="state.disabled" ref="TremD" :Trem="state.formData.TremD" Id="10006" title="违约条款"></EntryQualityInfo>
          </el-tab-pane>
          <el-tab-pane label="解除合同条款">
            <EntryQualityInfo :disabled="state.disabled" ref="TremTC" :Trem="state.formData.TremTC" Id="10005" title="解除合同条款"></EntryQualityInfo>
          </el-tab-pane>-->
          <el-tab-pane label="签收验收方式">
            <EntryOwner ref="TremYS" :disabled="state.disabled" :Trem="state.formData.TremYS" Id="10012" title="签收验收方式"></EntryOwner>
          </el-tab-pane>
<!--          <el-tab-pane label="其他">
            <EntryQualityInfo :disabled="state.disabled" ref="TremOther" :Trem="state.formData.TremOther" Id="10008" title="其他"></EntryQualityInfo>
          </el-tab-pane>
          <el-tab-pane label="保密约定">
            <EntryQualityInfo :disabled="state.disabled" ref="TremBM" :Trem="state.formData.TremBM" Id="10009" title="保密约定"></EntryQualityInfo>
          </el-tab-pane>-->
          <el-tab-pane label="交付条款">
            <EntryQualityInfo :disabled="state.disabled" ref="TremJF" :Trem="state.formData.TremJF" Id="10011" title="交付条框"></EntryQualityInfo>
          </el-tab-pane>
<!--          <el-tab-pane label="包装条款">
            <EntryQualityInfo :disabled="state.disabled" ref="TremBZ" :Trem="state.formData.TremBZ" Id="10010" title="包装条款"></EntryQualityInfo>
          </el-tab-pane>-->
          <el-tab-pane label="附件资料">
            <EntryAnnex :disabled="state.disabled" ref="ContractFile" :Trem="state.formData.ContractFile" title="附件资料"></EntryAnnex>
          </el-tab-pane>
        </el-tabs>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="submitForm" v-if="state.isShowSubBut" :loading="state.loading">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer
        v-model="state.drawer.open"
        :title="state.drawer.title"
        direction="rtl"
        size="50%"
    >
      <el-table :data="state.drawer.gridData">
        <el-table-column property="versionNum" label="版本号" width="150" />
        <el-table-column property="ContractNum" label="合同号" width="150" />
        <el-table-column property="State" label="状态">
          <template #default="scope">
            <el-tag type="info" v-if="scope.row.State=='0'">开立</el-tag>
            <el-tag type="success" v-if="scope.row.State=='11'">已审核</el-tag>
            <el-tag type="primary" v-if="scope.row.State=='12'">变更送审中</el-tag>
            <el-tag type="danger" v-if="scope.row.State=='13'">变更不通过</el-tag>
          </template>
        </el-table-column>
        <el-table-column property="updateDate" label="版本时间" width="200">
          <template #default="scope">
            {{ parseTime(scope.row.updateDate) }}
          </template>
        </el-table-column>
        <el-table-column property="updateBy" label="修改人" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script setup lang="tsx">
import { computed, onMounted, reactive, ref, toRefs, unref } from "vue"
import { getContractInfo, ApproveDocument, userRole } from "@/api/base"
import { delHT, getHTByPage, SaveHT, getContractVersion } from "@/api/contract_entry"
import { parseTime, debounce, checkPermission } from "@/utils/util";
import { cubasdocStore } from "@/stores/modules/cubasdoc";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import EntryBaseInfo from './components/base_info.vue'
import EntryQualityInfo from './components/quality_info.vue'
import EntryOwner from './components/ownership_info.vue'
import EntryAnnex from './components/annex_info.vue'
import { checkFildsStore } from "@/stores/modules/checkFilds";

const cubasdoc = cubasdocStore()
const handlEedit = async (row: any) => {
  clearCondition()
  //调用查询合同详细信息
  let res = await getContractInfo({ id: row.Id })

  if (res.Code === "OK") {
    state.formData = res.Data
    if (state.formData.Main.PhasedFile) {
      //转换为数组
      state.formData.Main.PhasedFile = state.formData.Main.PhasedFile.split(",")
    } else {
      state.formData.Main.PhasedFile = []
    }
    if (state.formData.Main.Payment) {
      //转换为数组
      state.formData.Main.Payment = state.formData.Main.Payment.split(",")
    } else {
      state.formData.Main.Payment = []
    }
    if (state.formData.Main.TDYSJDFile) {
      //转换为数组
      state.formData.Main.TDYSJDFile = state.formData.Main.TDYSJDFile.split(",")
    } else {
      state.formData.Main.TDYSJDFile = []
    }
    if (state.formData.Main.JHYSJDFile) {
      //转换为数组
      state.formData.Main.JHYSJDFile = state.formData.Main.JHYSJDFile.split(",")
    } else {
      state.formData.Main.JHYSJDFile = []
    }

    if (state.formData.Main.JSJDFile) {
      //转换为数组
      state.formData.Main.JSJDFile = state.formData.Main.JSJDFile.split(",")
    } else {
      state.formData.Main.JSJDFile = []
    }

    state.disabled = false
    state.formData.Type = "BJ"
    state.isShowSubBut = true
    state.dialogSelectEnt = true
    state.title = "修改合同模板"
  }
}

const updateCheck = async (row: any) => {
  clearCondition()
  //调用查询合同详细信息
  let res = await getContractInfo({ id: row.Id })

  if (res.Code === "OK") {
    state.formData = res.Data
    state.formData.Type = "BG"
    state.isShowSubBut = true
    state.dialogSelectEnt = true
    state.isBg = true
    state.title = "变更合同"
  }
}

const handlCheck = async (row: any, status: string) => {
  //调用查询合同详细信息
  //调用查询合同详细信息
  const ids = [row.Id];
  let data = {
    "Ids": ids,  //单据id
    "Type": "HTLR",  //类型 HTLR 合同录入 TDYS 通电验收  FHYS 发货验收  JSD 结算单  SKJH 收款计划 SKD 收款单 YKP 预收款发票
    "State": status,
  }
  await ApproveDocument(data);
  ElMessage.success("审核成功")
  await getData(1)
}

const handleView = async (row: any) => {
  //调用查询合同详细信息
  let res = await getContractInfo({ id: row.Id })

  if (res.Code === "OK") {
    state.formData = res.Data
    state.disabled = true
    state.dialogSelectEnt = true
    state.isShowSubBut = false
    state.title = "合同详情--" + row.ContractNum + "-v" + row.versionNum
  }
}

const selecttab = (vl) => {
  console.log(vl);
}

// 复用模板
const handlMultiplex = async (row: any) => {
  clearCondition()
  //调用查询合同详细信息
  let res = await getContractInfo({ id: row.Id })

  if (res.Code === "OK") {
    state.formData = res.Data
    state.formData.Main.Id = null
    state.dialogSelectEnt = true
    state.isShowSubBut = true
    state.title = "复用合同模板录入"
  }
}

const handleDelete = (row: any) => {
  state.clumTable.data.splice(state.clumTable.data.indexOf(row), 1)
}

// 添加重置查询函数
const resetQuery = () => {
  state.queryData = {
    ContractType: null,
    CustCode: null,
    CustName: null,
    ContractNum: null,
    CreateFrom: null,
    CreateTo: null,
    Type: null,
    CreateBy: null,
    IsMoudel: true
  }
  getData(1)
}

//表格配置
const state: any = reactive({
  roleList: [],
  disabled: false,
  queryData: {
    ContractType: null,//合同类型
    CustCode: null,//客户编码
    CustName: null,//客户名称
    ContractNum: null,//合同号
    CreateFrom: null,
    CreateTo: null,
    Type: null,
    CreateBy: null,//建单人
    IsMoudel: true
  },
  table: {
    border: true,
    total: 0,
    currentPage: 1,
    pageSize: 10,
    layout: "total,sizes, slot, prev, pager, next, jumper",
    prevText: "上一页",
    nextText: "下一页",
    // 接口返回数据
    data: [],
    firstColumn: { type: "selection", fixed: true },
    // 表头数据
    columns: [
      // { prop: "RewiewCode", label: "评审类型", minWidth: 120 },
      { prop: "CustCode", label: "客户编码", minWidth: 120 },
      { prop: "CustName", label: "客户名称", minWidth: 200 },
      { prop: "versionNum", label: "版本号", minWidth: 220 },
      { prop: "CustAdd", label: "客户地址", minWidth: 200 },
      { prop: "Type", label: "合同类型", minWidth: 120, slotName: "Type" },
      { prop: "IsMoudel", label: "是否合同模板", minWidth: 120, slotName: "IsMoudel" },
      { prop: "State", label: "状态", minWidth: 220, slotName: "State" },
      { prop: "BGState", label: "变更状态", minWidth: 220, slotName: "BGState" },
      // { prop: "ProjectName", label: "项目名称", minWidth: 200 },
      // { prop: "ContractAmount", label: "合同总价", minWidth: 160 },
      // { prop: "BankAccount", label: "银行账户", minWidth: 120 },
      // { prop: "Tax", label: "税号", minWidth: 200 },
      // { prop: "BankCode", label: "行号", minWidth: 160 },
      // { prop: "SigningLocation", label: "签订地点", minWidth: 160},
      // { prop: "DeliveryDate", label: "交付时间", minWidth: 160,slotName: "DeliveryDate"},
      // { prop: "DeliveryLocation", label: "交付地点", minWidth: 160},


      // { prop: "DDate", label: "单据日期", minWidth: 220,slotName: "DDate"},
      { prop: "createDate", label: "创建时间", minWidth: 220, slotName: "CreateDate" },
      // { prop: "createBy", label: "建单人", minWidth: 220 },
      {
        prop: "operator",
        label: "操作",
        minWidth: "320",
        fixed: "right",
        slotName: "operator"
      }
    ],
    // operator: [
    //   {
    //     text: "编辑",
    //     fun: handlEedit
    //   },
    //   {
    //     text: "删除",
    //     fun: deleteHandles
    //   }
    // ],
    // 操作列样式
    operatorConfig: {
      fixed: "right", // 固定列表右边（left则固定在左边）
      width: 300,
      label: "操作"
    }
  },
  loading: false,
  isShowSubBut: true,
  isBg: false,
  title: "新增合同模板录入",
  dialogSelectEnt: false,
  //表单
  formData: {
    Main: {
    },
    SubList: [],
    TremZF: [],
    TremTO: [],
    TremTC: [],
    TremQA: [],
    TremFM: [],
    TremDR: [],
    TremD: [],
    TremOther: [],
    TremYS: [],
    TremBM: [],
    TremJF: [],
    TremBZ: [],
    ContractFile: []
  },
  coseData: [],

  clumTable: {
    border: true,
    firstColumn: { type: "selection" },
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      {
        prop: "CinvCode",
        label: "设备编码",
      },
      {
        prop: "CinvName",
        label: "设备名称",
      },
      {
        prop: "CinvAdd",
        label: "规格型号",

      },
      // {
      //   prop: "Price",
      //   label: "单价",
      //   canEdit: true,
      //   configEdit: {
      //     label: "数量",
      //     type: "input",
      //     editComponent: "el-input"
      //   }
      // },
      {
        prop: "Qty",
        label: "数量",
        canEdit: true,
        configEdit: {
          label: "数量",
          type: "input",
          editComponent: "el-input"
        }
      },
      // {
      //   prop: "Amount",
      //   label: "金额",
      //   canEdit: true,
      //   configEdit: {
      //     label: "数量",
      //     type: "input",
      //     editComponent: "el-input"
      //   }
      // },
      {
        prop: "Unit",
        label: "单位",

      },

    ],
    listTypeInfo: {
      furnaceLayerList: [
        {
          label: "上层",
          key: "1"
        },
        {
          label: "中层",
          key: "2"
        },
        {
          label: "下层",
          key: "3"
        }
      ]
    },
    operator: [
      {
        text: "删除",
        fun: handleDelete
      }
    ],
    // 操作列样式
    operatorConfig: {
      fixed: "right", // 固定列表右边（left则固定在左边）
      width: 300,
      label: "操作"
    }
  },
  editTable: {
    border: true,
    firstColumn: { type: "selection" },
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      {
        prop: "CinvCode",
        label: "设备编码",
      },
      {
        prop: "CinvName",
        label: "设备名称",
      },
      {
        prop: "CinvAdd",
        label: "规格型号",

      },
      {
        prop: "Quantity",
        label: "数量",
      },
      {
        prop: "Unit",
        label: "单位",

      },

    ],
    listTypeInfo: {
      furnaceLayerList: [
        {
          label: "上层",
          key: "1"
        },
        {
          label: "中层",
          key: "2"
        },
        {
          label: "下层",
          key: "3"
        }
      ]
    },
    operator: [
      {
        text: "删除",
        fun: handleDelete
      }
    ],
    // 操作列样式
    operatorConfig: {
      fixed: "right", // 固定列表右边（left则固定在左边）
      width: 200,
      label: "操作"
    }
  },

  rules: {
    ContractName: [
      { required: true, message: '请输入合同名称', trigger: 'blur' },
    ],
    ContractNum: [
      { required: true, message: '请输入合同编号', trigger: 'blur' },
    ],
    // ProjectName: [
    //   { required: true, message: '请输入项目名称', trigger: 'blur' },
    // ],
    // CustCode: [
    //   { required: true, message: '请选择客户', trigger: 'change' },
    // ],
    ContractType: [
      { required: true, message: '请选择合同类型', trigger: 'change' },
    ],
    // PSType: [
    //   { required: true, message: '请输入评审类型', trigger: 'blur' },
    // ],
    // Payment: [
    //   { required: true, message: '请选择支付款项', trigger: 'change' },
    // ],
    // BankCode: [
    //   { required: true, message: '请输入开户行', trigger: 'blur' },
    // ],
    // BankAccount: [
    //   { required: true, message: '请输入银行账号', trigger: 'blur' },
    // ],
    // Tax: [
    //   { required: true, message: '请输入税号', trigger: 'blur' },
    // ],
    // IsCompliance: [
    //   { required: true, message: '请选择标的物是否合规', trigger: 'change' },
    // ],
    // DeliveryDate: [
    //   { required: true, message: '请选择交付时间', trigger: 'change' },
    // ],
    // DeliveryLocation: [
    //   { required: true, message: '请输入交付地点', trigger: 'blur' },
    // ],
    // Rate: [
    //   { required: true, message: '请输入税率', trigger: 'blur' },
    // ],
    // Unload: [
    //   { required: true, message: '请选择卸货方式', trigger: 'change' },
    // ],
    // PackRequirement: [
    //   { required: true, message: '请输入包装要求', trigger: 'blur' },
    // ],
    // ContractAmount: [
    //   { required: true, message: '请输入合同金额', trigger: 'blur' },
    // ],
    // UnloadConvention: [
    //   { required: true, message: '请输入补充说明', trigger: 'blur' },
    // ],
    // SigningLocation: [
    //   { required: true, message: '请输入签订地点', trigger: 'blur' },
    // ],
    // IsMoudel: [
    //   { required: true, message: '请选择合同是否合同模板', trigger: 'change' },
    // ],
    // Ddate: [
    //   { required: true, message: '请选择签订日期', trigger: 'blur' },
    // ],
    // DDate2: [
    //   { required: true, message: '请选择单据日期', trigger: 'blur' },
    // ],
    // JobNum: [
    //   { required: true, message: '工作号', trigger: 'blur' },
    // ],
    // SaleNum: [
    //   { required: true, message: '售前号', trigger: 'blur' },
    // ],
    // Change: [
    //   { required: true, message: '请输入变更原因', trigger: 'blur' },
    // ],
    PhasedFile: [
      { required: true, message: '请选择阶段性文件', trigger: 'change' },
    ],
  },
  defaultSelectVal: [],
  ids: [],
  drawer: {
    open: false,
    title: "历史版本",
    width: "1000px",
    gridData: []
  }

})

// 最终参数获取
const getQueryData = computed(() => {
  const data = toRefs(state.queryData)
  //转换查询参数
  return {
    ContractType: data.ContractType?.value,
    CustCode: data.CustCode?.value,
    CustName: data.CustName?.value,
    CreateBy: data.CreateBy?.value,
    PSType: data.PSType?.value,
    IsMoudels: true,
    State: data.State?.value,
    Type: data.Type?.value,
    CreateFrom: data.CreateFrom?.value && data.CreateFrom?.value[0] ? data.CreateFrom?.value[0] : null,
    CreateTo: data.CreateFrom?.value && data.CreateFrom?.value[1] ? data.CreateFrom?.value[1] : null,
  }
})

// 点击查询按钮
const conditionEnter = (data: any) => {
  state.queryData = data
  getData(1)
}

// 清空表单
const clearCondition = () => {
  state.formData = {
    Main: {},
    SubList: [],
    TremZF: [],
    TremTO: [],
    TremTC: [],
    TremQA: [],
    TremFM: [],
    TremDR: [],
    TremD: [],
    TremOther: [],
    TremYS: [],
    TremBM: [],
    TremJF: [],
    TremBZ: [],
    ContractFile: []
  }
}

// 选择当前页码
const sizeChange = val => {
  state.table.pageSize = val
  getData()
}

// 选择当前页码
const pageChange = val => {
  state.table.currentPage = val
  getData()
}

// 获取数据
const getData = async () => {
  state.loading = true
  getQueryData.value.PageIndex = state.table.currentPage
  getQueryData.value.PageSize = state.table.pageSize
  let data = await getHTByPage(getQueryData.value);

  if (data.Code === 'OK') {
    state.table.data = data.Data
    state.table.total = data.Count
  }
  state.loading = false
}

function updateContarctInfo(e) {
  //查询过滤合同信息
  let contractInfo = cubasdoc.contractList.find(item => item.ContractNum === e);
  if (contractInfo) {
    //赋值项目名称
    state.formData.EntryName = contractInfo?.ProjectName;
    state.formData.JobNum = contractInfo?.JobNum;

    //调用查询合同详细信息
    findContractInfo(contractInfo.Id)
  }
}

//查询合同详细信息
async function findContractInfo(id) {
  let { Data } = await getContractInfo({ id: id })

  if (Data?.SubList) {
    //赋值合同明细
    state.editTable.data = Data.SubList
  }
}

//打开新增窗口
function addHandle() {
  clearCondition()
  state.formData.Main = {
    Ddate: parseTime(new Date(), "{y}-{m}-{d}"),
    DDate2: parseTime(new Date(), "{y}-{m}-{d}"),
    Rate: 13,
    IsMoudels: true,
    IsMoudel: '是',
  }
  state.disabled = false
  state.title = "新增模版"
  state.dialogSelectEnt = true
  state.isShowSubBut = true
}

//打开新增窗口
function importHandle() {
}

//关闭弹窗
function closeDialog() {
  state.dialogSelectEnt = false
  reset()
}

// 添加数据条数
const num = ref(1)
const singleEdit: any = ref(null)
// 添加数据
const add = () => {
  if (num.value > 0) {
    for (let i = 0; i < num.value; i++) {
      state.editTable.data.push({})
    }
  }
}
// 重置表单
const reset = () => {
  state.coseData = []
  state.defaultSelectVal = []
  state.editTable.data = []
  singleEdit.value?.resetFields()
}

//下拉表格选择数据
const selectionChange = (e) => {
  state.coseData = e
}

//下拉表格选择数据
const selecUpdateChange = (e) => {
  state.ids = e.map(item => item.Id)
}

//选择标的
const addToTable = () => {
  if (state.coseData.length <= 0) {
    ElNotification.warning({
      title: '提示',
      message: '请选择标的',
      offset: 200,
    })
    return
  }

  state.coseData.forEach(item => {
    //相同数据不能添加
    if (state.clumTable.data.find(item1 => item1.Id === item.Id || item1.ConSubId === item.Id)) {
      ElNotification.warning({
        title: '提示',
        message: item.CinvName + '已存在，请勿重复添加',
        offset: 200,
      })
      return
    }
    let Qty = {
      ...item,
      Qty: item.Quantity,
      ConSubId: item.Id
    }
    state.clumTable.data.push(Qty)
  })
}

//校验表单需要定义ref
let formRef = ref({})
let TremTO = ref({})
let TremTC = ref({})
let TremQA = ref({})
let TremFM = ref({})
let TremDR = ref({})
let TremD = ref({})
let TremBM = ref({})
let TremOther = ref({})
let TremYS = ref({})
let TremJF = ref({})
let TremBZ = ref({})
let ContractFile = ref({})

const checkFild = checkFildsStore()
// 提交表单

//获取条款内容
const submitForm = debounce(async () => {
  checkFild.cliear()
  state.loading = true
  try {
    setTimeout(async () => {
      if (checkFild.filds.length == 0) {
        const data = JSON.parse(JSON.stringify(state.formData))

        // Process array fields
        const arrayFields = ['PhasedFile', 'Payment', 'JSJDFile', 'TDYSJDFile', 'JHYSJDFile','YSZLFile']
        arrayFields.forEach(field => {
          if (data.Main[field]?.length > 0) {
            data.Main[field] = state.formData.Main[field].join(',')
          } else {
            data.Main[field] = ''
          }
        })

        let res =await SaveHT(data)
        //校验通过
        if (res.Code === 'OK') {
          ElNotification.success({
            title: '提示',
            message: '保存成功',
            offset: 200
          })
          setTimeout(async () => {
            await getData()
          }, 1000)
          closeDialog()
        } else {
          ElNotification.error({
            title: '提示',
            message: res.Result,
            offset: 200
          })
        }
      }
    }, 2000)
  }catch (e) {
    state.loading = false
  }finally {
    state.loading = false
  }


}, false, 1000)

function printHandle(res) {
  window.open(import.meta.env.VITE_APP_PRINT_API + res.Id)
}

async function versionHandle(res) {
  //查询版本
  let { Data, Code } = await getContractVersion({ ContractNum: res.ContractNum, versionNum: res.versionNum, BaseCode: res.BaseCode })
  if (Code === 'OK') {
    state.drawer.gridData = Data
    state.drawer.open = true
  }
}

//删除表单
function deleteHandles(row) {
  const ids = row.Id ? [row.Id] : state.ids;

  ElMessageBox.confirm(
      '请仔细核对数据，删除后无法恢复！',
      '审核提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(async () => {
        let res = await delHT({ Ids: ids })
        if (res.Code === 'OK') {
          ElNotification.success({
            title: '提示',
            message: '删除成功',
            offset: 200,
          })
          await getData(1)
        } else
          ElNotification.error({
            title: '提示',
            message: res.Result,
            offset: 200,
          })
      })
      .catch(() => {
      })
}

//页面加载查询后端数据
onMounted(() => {
  getData(1)
  initRoleList()
})

const initRoleList = async () => {
  let res = await userRole({ VT_ID: '合同模板' })
  state.roleList = res.items
}
</script>

<style scoped>.contract-model-page {
  padding: 20px;
  background-color: #fff;
}

.query-form {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.query-form .el-form-item {
  margin-bottom: 15px;
}

.query-buttons {
  display: flex;
  align-items: flex-end;
  height: 100%;
  padding-bottom: 5px;
}

.query-buttons .el-button {
  margin-right: 10px;
}

.table-toolbar {
  margin-bottom: 15px;
}
</style>
